package muilty_thread.java_current_practice_and_kernel.cp7;

import java.io.PrintWriter;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class LogWriter {
    private final BlockingQueue<String> blockingQueue;
    private final LoggerThread thread;
    private static boolean shutdownRequest;

    public LogWriter(PrintWriter writer) {
        this.blockingQueue = new LinkedBlockingQueue<>();
        this.thread = new LoggerThread(writer);
        shutdownRequest = false;
    }

    public void start(){
        thread.start();
    }

    public void log(String msg) throws InterruptedException {
        if (!shutdownRequest) {
            blockingQueue.put(msg);
        }else {
            throw new InterruptedException();
        }

    }


    public class LoggerThread extends Thread{
        PrintWriter writer;

        public LoggerThread(PrintWriter writer) {
            this.writer = writer;
        }

        @Override
        public void run() {

            try {
                while (true) {
                    String take = blockingQueue.take();
                    writer.println(take);
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }


        }
    }
}
